Ext.define('Baoy.controller.system.SystemMainController', {
	extend : 'Ext.app.ViewController',
	alias : 'controller.system-main-controller',

	onSystemClick : function(tree, record, item, index) {
		if (record.isLeaf()) {
			this.showTab(record.get('id'), record.get('text'), record.get('glyph'));
			return ;
		}
		record.expand();
	},

	showTab : function(tabId, title, glyph) {
		var tabPanel = this.getView().down('tabpanel');
		var tab = tabPanel.items.findBy(function(item) {
			if (item.id == tabId) {
				return true;
			}
		});
		if (!tab) {
			tab = tabPanel.add({
				id : tabId,
				layout : 'fit',
				title : title,
				items : [ {
					xtype : 'system-' + tabId + '-view'// xtype不存在，可能会抛出异常 
				} ],
				glyph : glyph || ''
			})
		}
		if (tab) {
			tabPanel.setActiveTab(tab);
		}
	},

	onTabChange : function(tabs, newTab, oldTab) {
		var treePanel = this.getView().down('treepanel');
		var selectNode = treePanel.getStore().getNodeById(newTab.getId());
		if (selectNode) {
			treePanel.setSelection(selectNode);
		}
	},

	onOpenFirstNode : function(me, e) {
		var rootNode = me.getStore().getRootNode();
		Ext.defer(function() {
			if (rootNode.childNodes && rootNode.childNodes.length > 0) {
				var selectNode = rootNode.childNodes[0];
				this.setSelection(selectNode);
				this.fireEvent('itemclick', this, selectNode);
			}
		}, 100, me);
	}
})